package com.example.jobseek;

import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.example.jobseek.Login.log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import domain.PersonaVO;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class EditarPerfil extends ActionBarActivity {

	Bundle bundle;
	String datosP;
	String rutP;
	JsonObject jobj;
	JSONArray datos;
    JSONObject persona;
    EditText etNombre;
    EditText etApellido;
    EditText etCiudad;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_editar_perfil);
		bundle = this.getIntent().getExtras();
        datosP = bundle.getString("datos");
        rutP = bundle.getString("rut");
        System.out.println(datosP);
        System.out.println(rutP);
        etNombre = (EditText)findViewById(R.id.etNombre);
        etApellido = (EditText)findViewById(R.id.etApellido);
        etCiudad = (EditText)findViewById(R.id.etCiudad);
        Button b = (Button)findViewById(R.id.aceptar);
        
        try {
        	jobj = new Gson().fromJson(rutP, JsonObject.class);
			datos = new JSONArray(datosP);
			persona = datos.getJSONObject(0);
			etNombre.setText(persona.getString("nombre"));
			etApellido.setText(persona.getString("apellido"));
			etCiudad.setText(persona.getString("ciudad"));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        
        
        
        b.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				new edit().execute(jobj.get("run").toString().replace("\"", ""), etNombre.getText().toString(),
						etApellido.getText().toString(), etCiudad.getText().toString());
				
			}});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.editar_perfil, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	class edit extends AsyncTask<String, Void, String>{
        private static final String TAG = "editarPerfil";
        ProgressDialog progressDialog;
        
        @Override
        protected void onPreExecute(){
                super.onPreExecute();
                progressDialog = ProgressDialog.show(EditarPerfil.this, "Cargando...", "Espere..",
                                true, true);
                
        }
        
        @Override
        protected String doInBackground(String... params) {
                String run = params[0];
                String nombre = params[1];
                String apellido = params[2];
                String ciudad = params[3];
                String result="";

                try {
               	 
               	 PersonaVO personaVO = new PersonaVO(run, "", nombre, apellido, ciudad);
               	 
               	 result = editarPerfil(personaVO);
                                
               	 Log.i(TAG, result);
                        
                } catch (Exception e) {
                        Log.e(TAG, e.getCause().toString());
                }

                return result;
        }
        
        @Override
        protected void onPostExecute(String result) {
                super.onPostExecute(result);
                progressDialog.dismiss();
                

                if ("".equals(result)) {
                        Toast.makeText(EditarPerfil.this, "Existe problemas de conectividad con el servidor",Toast.LENGTH_SHORT).show();
                } else if (result.contains("Error")){
               	 Toast.makeText(getApplicationContext(),result , Toast.LENGTH_LONG).show();
                }else{  
                        Bundle b = new Bundle();
                        b.putString("rut", rutP);
                        Intent i = new Intent(EditarPerfil.this, Perfil.class);
                        i.putExtras(b);
        			    startActivity(i);
                
                        
        }

}
}
	
	public String editarPerfil(PersonaVO oPersonaVO){
		String result ="";
		
		String method = "editarPerfil";
		String TAG = method;
		Log.i("intentando enviar datos al ws usando: ", method);

		try {
			String SOAP_ACTION = util.Constantes.NAMESPACE + "#" + method;

			SoapObject request = new SoapObject(util.Constantes.NAMESPACE,
					method);

			Gson gson = new Gson();
			String persona = gson.toJson(oPersonaVO);

			request.addProperty("json", persona);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER12);

			envelope.setOutputSoapObject(request);

			envelope.addMapping(util.Constantes.NAMESPACE, "PersonaVO",
					new PersonaVO().getClass());

			HttpTransportSE transporte = new HttpTransportSE(
					util.Constantes.URL);
			transporte.debug = true;

			transporte.call(SOAP_ACTION, envelope);

			Log.i(TAG, "dump Request: " + transporte.requestDump);
			Log.i(TAG, "dump Response: " + transporte.responseDump);

			Vector response = (Vector) envelope.getResponse();
			result = (String)response.get(1);
			return result;

		} catch (Exception e) {
			e.printStackTrace();

		}

		return null;
	}
}
